<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\kdniao\request;

use extend\kdniao\BaseRequest;
use extend\kdniao\Header;
use extend\kdniao\Kdniao;
use yii\helpers\Json;

/**
 * 物流轨迹即时查询
 * ```php
 *  //创建物流轨迹查询服务实例
 *  $trackQueryRequest = TrackQueryRequest::createObject();
 *  $trackQueryRequest->setParamShipperCode('SF')
 *       ->setParamLogisticCode('SF8880241669912')
 *       ->setParamCustomerName('1196');
 *
 *  //创建快递鸟客户端
 *  $kdniao = Kdniao::createObject();
 *  $execState = $kdniao->setRequest($trackQueryRequest)->execute();
 *  if ($execState) {
 *      return $kdniao->result;
 *  } else {
 *      return $kdniao->error;
 *  }
 *
 *  ```
 *
 * @author clevstn
 * @since ym2.0
 */
class TrackQueryRequest extends BaseRequest
{
    //服务请求地址
    private $_requestUri = 'Ebusiness/EbusinessOrderHandle.aspx';
    //服务指令标识
    private $_requestType = '8001';
    //请求、返回数据类型：2-json；
    private $_dataType = '2';
    //请求内容需进行URL(utf-8)编码。请求内容JSON格式，须和DataType一致。
    private $_requestData = [
        'Sort' => 1, //轨迹按时间排序，0-升序，1-降序，默认0
    ];

    /**
     * @param string $shipperCode 快递公司编码
     * @return $this
     */
    public function setParamShipperCode($shipperCode)
    {
        $this->_requestData['ShipperCode'] = $shipperCode;
        return $this;
    }

    /**
     * @param string $logisticCode 快递单号
     * @return $this
     */
    public function setParamLogisticCode($logisticCode)
    {
        $this->_requestData['LogisticCode'] = $logisticCode;
        return $this;
    }

    /**
     * @param string $mobileLastFour
     *  顺丰必填
     *  寄件人or收件人 手机号后四位
     *  虚拟号后四位不可用
     *  后四位传值错误无法获取到顺丰轨迹（可能拉取缓存）
     *  后四位正确性可通过微信小程序【顺丰速运+】验证
     * @return $this
     */
    public function setParamCustomerName($mobileLastFour)
    {
        $this->_requestData['CustomerName'] = $mobileLastFour;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestParams()
    {
        $requestData = Json::encode($this->_requestData);
        return [
            'EBusinessID' => Kdniao::E_BUSINESS_ID,
            'RequestType' => $this->_requestType,
            'RequestData' => urlencode($requestData),
            'DataType' => $this->_dataType,
            'DataSign' => Kdniao::generateSign($requestData),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function getServiceName()
    {
        return '物流轨迹查询';
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestUrl()
    {
        return self::API_DOMAIN . $this->_requestUri;
    }

    /**
     * {@inheritDoc}
     */
    public function triggerResponseCallback(Kdniao $kdniao)
    {
        if (!$kdniao->hasError()) {//Success
            $result = Json::decode($kdniao->result);
            if ($result['Success'] && !empty($result['Traces'])) {
                $result['StateLabel'] = Header::$stateLabel[$result['State']];
                $result['StateExLabel'] = Header::$stateExLabel[$result['StateEx']];
                foreach ($result['Traces'] as &$item) {
                    $item['ActionLabel'] = Header::$stateExLabel[$item['Action']];
                }

                $kdniao->result = $result;
            } else {
                $kdniao->error = $result['Reason'];
            }
        }
    }
}